// DOM元素选择
const navItems = document.querySelectorAll('.nav-item');
const pages = document.querySelectorAll('.page');
const authModal = document.getElementById('authModal');
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const closeAuthModal = document.getElementById('closeAuthModal');
const switchToRegister = document.getElementById('switchToRegister');
const switchToLogin = document.getElementById('switchToLogin');
const loginBtn = document.getElementById('loginBtn');
const registerBtn = document.getElementById('registerBtn');
const logoutBtn = document.getElementById('logoutBtn');
const userName = document.getElementById('userName');
const dropdownUserName = document.getElementById('dropdownUserName');
const dropdownUserRole = document.getElementById('dropdownUserRole');
const userMenuBtn = document.getElementById('userMenuBtn');
const userDropdown = document.getElementById('userDropdown');
const notificationBtn = document.getElementById('notificationBtn');
const notificationPanel = document.getElementById('notificationPanel');
const togglePasswordBtns = document.querySelectorAll('.toggle-password');
const checkinBtn = document.getElementById('checkinBtn');
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toastMessage');
const submitAssignmentBtns = document.querySelectorAll('.submit-assignment');
const submitModal = document.getElementById('submitModal');
const closeSubmitModal = document.getElementById('closeSubmitModal');
const cancelSubmit = document.getElementById('cancelSubmit');
const submitAssignmentForm = document.getElementById('submitAssignmentForm');
const fileInput = document.getElementById('fileInput');
const fileNames = document.getElementById('fileNames');
const newThreadBtn = document.getElementById('newThreadBtn');
const threadModal = document.getElementById('threadModal');
const closeThreadModal = document.getElementById('closeThreadModal');
const cancelThread = document.getElementById('cancelThread');
const newThreadForm = document.getElementById('newThreadForm');
const threadFileInput = document.getElementById('threadFileInput');
const threadFileNames = document.getElementById('threadFileNames');
const leaveForm = document.getElementById('leaveForm');
const leaveAttachment = document.getElementById('leaveAttachment');
const attachmentName = document.getElementById('attachmentName');
const markAllReadBtn = document.getElementById('markAllRead');
const markAllReadPageBtn = document.getElementById('markAllReadPage');
const notificationFilter = document.getElementById('notificationFilter');
const notificationsFilterPage = document.getElementById('notificationsFilterPage');
const notificationItems = document.querySelectorAll('.notification-item');

// 页面导航切换
navItems.forEach(item => {
    item.addEventListener('click', (e) => {
        e.preventDefault();
        
        // 移除所有活动状态
        navItems.forEach(nav => nav.classList.remove('active'));
        pages.forEach(page => page.classList.remove('active'));
        
        // 添加当前活动状态
        item.classList.add('active');
        const targetId = item.getAttribute('data-target');
        document.getElementById(targetId).classList.add('active');
        
        // 关闭可能打开的下拉菜单
        userDropdown.classList.add('hidden');
        notificationPanel.classList.add('hidden');
    });
});

// 模态框控制
function openModal(modal) {
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeModal(modal) {
    modal.style.display = 'none';
    document.body.style.overflow = 'auto';
}

// 登录注册模态框
loginBtn.addEventListener('click', () => {
    openModal(authModal);
    loginForm.classList.remove('hidden');
    registerForm.classList.add('hidden');
    document.getElementById('authTitle').textContent = '登录';
    userDropdown.classList.add('hidden');
});

registerBtn.addEventListener('click', () => {
    openModal(authModal);
    registerForm.classList.remove('hidden');
    loginForm.classList.add('hidden');
    document.getElementById('authTitle').textContent = '注册';
    userDropdown.classList.add('hidden');
});

closeAuthModal.addEventListener('click', () => {
    closeModal(authModal);
});

switchToRegister.addEventListener('click', (e) => {
    e.preventDefault();
    loginForm.classList.add('hidden');
    registerForm.classList.remove('hidden');
    document.getElementById('authTitle').textContent = '注册';
});

switchToLogin.addEventListener('click', (e) => {
    e.preventDefault();
    registerForm.classList.add('hidden');
    loginForm.classList.remove('hidden');
    document.getElementById('authTitle').textContent = '登录';
});

// 用户菜单切换
userMenuBtn.addEventListener('click', () => {
    userDropdown.classList.toggle('hidden');
    notificationPanel.classList.add('hidden');
});

// 通知面板切换
notificationBtn.addEventListener('click', () => {
    notificationPanel.classList.toggle('hidden');
    userDropdown.classList.add('hidden');
});

// 点击外部关闭下拉菜单
document.addEventListener('click', (e) => {
    if (!userMenuBtn.contains(e.target) && !userDropdown.contains(e.target)) {
        userDropdown.classList.add('hidden');
    }
    
    if (!notificationBtn.contains(e.target) && !notificationPanel.contains(e.target)) {
        notificationPanel.classList.add('hidden');
    }
    
    if (authModal.style.display === 'flex' && !authModal.contains(e.target) && 
        e.target !== loginBtn && e.target !== registerBtn) {
        closeModal(authModal);
    }
});

// 密码显示切换
togglePasswordBtns.forEach(btn => {
    btn.addEventListener('click', (e) => {
        e.preventDefault();
        const targetId = btn.getAttribute('data-target');
        const passwordInput = document.getElementById(targetId);
        const icon = btn.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });
});

// 登录功能
loginForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // 模拟登录成功
    const email = document.getElementById('loginEmail').value;
    if (email) {
        const username = email.split('@')[0];
        userName.textContent = username;
        dropdownUserName.textContent = username;
        dropdownUserRole.textContent = '学生';
        loginBtn.classList.add('hidden');
        registerBtn.classList.add('hidden');
        logoutBtn.classList.remove('hidden');
        closeModal(authModal);
        showToast('登录成功');
        loginForm.reset();
    }
});

// 注册功能
registerForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // 模拟注册成功
    const name = document.getElementById('regName').value;
    if (name) {
        closeModal(authModal);
        showToast('注册成功，请登录');
        registerForm.reset();
    }
});

// 登出功能
logoutBtn.addEventListener('click', () => {
    userName.textContent = '请登录';
    dropdownUserName.textContent = '请登录';
    dropdownUserRole.textContent = '未登录';
    loginBtn.classList.remove('hidden');
    registerBtn.classList.remove('hidden');
    logoutBtn.classList.add('hidden');
    userDropdown.classList.add('hidden');
    showToast('已退出登录');
});

// 签到功能
checkinBtn.addEventListener('click', () => {
    checkinBtn.innerHTML = '<i class="fa fa-check"></i> 已签到';
    checkinBtn.disabled = true;
    checkinBtn.classList.add('secondary-btn');
    checkinBtn.classList.remove('primary-btn');
    document.querySelector('.checkin-status').textContent = '已签到';
    document.querySelector('.checkin-status').classList.remove('pending');
    document.querySelector('.checkin-status').classList.add('completed');
    showToast('签到成功');
});

// 提交作业模态框
submitAssignmentBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const assignmentId = btn.getAttribute('data-id');
        document.getElementById('assignmentId').value = assignmentId;
        openModal(submitModal);
    });
});

closeSubmitModal.addEventListener('click', () => {
    closeModal(submitModal);
});

cancelSubmit.addEventListener('click', () => {
    closeModal(submitModal);
});

// 文件上传显示文件名
fileInput.addEventListener('change', () => {
    if (fileInput.files.length > 0) {
        if (fileInput.files.length === 1) {
            fileNames.textContent = fileInput.files[0].name;
        } else {
            fileNames.textContent = `${fileInput.files.length} 个文件`;
        }
    } else {
        fileNames.textContent = '未选择文件';
    }
});

// 请假附件上传显示文件名
leaveAttachment.addEventListener('change', () => {
    if (leaveAttachment.files.length > 0) {
        attachmentName.textContent = leaveAttachment.files[0].name;
    } else {
        attachmentName.textContent = '未选择文件';
    }
});

// 提交作业功能
submitAssignmentForm.addEventListener('submit', (e) => {
    e.preventDefault();
    if (fileInput.files.length > 0) {
        const assignmentId = document.getElementById('assignmentId').value;
        // 更新对应作业状态
        const submitBtn = document.querySelector(`.submit-assignment[data-id="${assignmentId}"]`);
        const assignmentCard = submitBtn.closest('.assignment-card');
        const statusElement = assignmentCard.querySelector('.assignment-status');
        
        statusElement.textContent = '已提交';
        statusElement.classList.remove('pending');
        statusElement.classList.add('submitted');
        
        // 添加提交信息
        const descriptionElement = assignmentCard.querySelector('.assignment-description');
        const submissionInfo = document.createElement('div');
        submissionInfo.className = 'submission-info';
        submissionInfo.innerHTML = `<i class="fa fa-check-circle"></i>
                                    <span>已提交：${fileInput.files[0].name}</span>
                                    <span>提交时间：${new Date().toLocaleString()}</span>`;
        descriptionElement.appendChild(submissionInfo);
        
        // 更改按钮
        assignmentCard.querySelector('.assignment-actions').innerHTML = 
            '<button class="primary-btn">查看成绩</button>';
        
        closeModal(submitModal);
        showToast('作业提交成功');
        submitAssignmentForm.reset();
        fileNames.textContent = '未选择文件';
    } else {
        showToast('请选择要上传的文件', false);
    }
});

// 发布主题模态框
newThreadBtn.addEventListener('click', () => {
    openModal(threadModal);
});

closeThreadModal.addEventListener('click', () => {
    closeModal(threadModal);
});

cancelThread.addEventListener('click', () => {
    closeModal(threadModal);
});

// 主题附件上传显示文件名
threadFileInput.addEventListener('change', () => {
    if (threadFileInput.files.length > 0) {
        threadFileNames.textContent = threadFileInput.files[0].name;
    } else {
        threadFileNames.textContent = '未选择文件';
    }
});

// 发布主题功能
newThreadForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const title = document.getElementById('threadTitle').value;
    const content = document.getElementById('threadContent').value;
    const category = document.getElementById('threadCategory').value;
    
    if (title && content && category) {
        // 模拟添加新主题到列表
        const forumBody = document.querySelector('.forum-body');
        const categoryMap = {
            'question': '问题求助',
            'share': '经验分享',
            'discussion': '技术讨论',
            'lab': '实验室相关',
            'other': '其他'
        };
        
        const newThread = document.createElement('div');
        newThread.className = 'thread-item';
        newThread.innerHTML = `
            <div class="forum-column topic-column">
                <div class="thread-info">
                    <h4><a href="#">${title}</a></h4>
                    <p>${content.substring(0, 50)}${content.length > 50 ? '...' : ''}</p>
                    <div class="thread-tags">
                        <span class="tag ${category}">${categoryMap[category]}</span>
                    </div>
                </div>
            </div>
            <div class="forum-column author-column">
                <div class="user-info">
                    <img src="https://picsum.photos/id/64/100/100" alt="用户头像">
                    <span>${userName.textContent}</span>
                </div>
            </div>
            <div class="forum-column replies-column">
                <span>0</span>
            </div>
            <div class="forum-column last-post-column">
                <div class="last-post-info">
                    <span>${userName.textContent}</span>
                    <span>刚刚</span>
                </div>
            </div>
        `;
        
        // 添加到列表顶部
        forumBody.insertBefore(newThread, forumBody.firstChild);
        
        closeModal(threadModal);
        showToast('主题发布成功');
        newThreadForm.reset();
        threadFileNames.textContent = '未选择文件';
    } else {
        showToast('请填写标题、内容并选择分类', false);
    }
});

// 请假申请功能
leaveForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const startDate = document.getElementById('leaveStart').value;
    const endDate = document.getElementById('leaveEnd').value;
    const reason = document.getElementById('leaveReason').value;
    const leaveType = document.getElementById('leaveType').value;
    
    if (startDate && endDate && reason && leaveType) {
        // 模拟添加新请假记录
        const leaveRecords = document.querySelector('.leave-records');
        const typeMap = {
            'sick': '病假',
            'personal': '事假',
            'late': '迟到',
            'early': '早退'
        };
        
        const newRecord = document.createElement('div');
        newRecord.className = 'leave-record';
        newRecord.innerHTML = `
            <div class="record-header">
                <h4>${typeMap[leaveType]}</h4>
                <span class="status pending">待审批</span>
            </div>
            <div class="record-details">
                <p><i class="fa fa-calendar"></i> ${formatDate(startDate)} 至 ${formatDate(endDate)}</p>
                <p><i class="fa fa-clock-o"></i> 申请时间：${new Date().toLocaleString()}</p>
                <p><i class="fa fa-user"></i> 审批人：待审批</p>
            </div>
        `;
        
        // 添加到列表顶部
        leaveRecords.insertBefore(newRecord, leaveRecords.firstChild);
        
        showToast('请假申请提交成功，等待审批');
        leaveForm.reset();
        attachmentName.textContent = '未选择文件';
    } else {
        showToast('请填写完整的请假信息', false);
    }
});

// 通知标为已读
markAllReadBtn.addEventListener('click', () => {
    markAllNotificationsAsRead();
});

markAllReadPageBtn.addEventListener('click', () => {
    markAllNotificationsAsRead();
});

function markAllNotificationsAsRead() {
    notificationItems.forEach(item => {
        item.classList.remove('unread');
    });
    
    // 隐藏所有徽章
    document.querySelectorAll('.nav-badge').forEach(badge => {
        badge.classList.add('hidden');
    });
    document.querySelectorAll('.notification-badge').forEach(badge => {
        badge.classList.add('hidden');
    });
    
    showToast('所有通知已标为已读');
}

// 单个通知标为已读
document.querySelectorAll('.mark-read').forEach(btn => {
    btn.addEventListener('click', (e) => {
        e.preventDefault();
        const notificationItem = btn.closest('.notification-item');
        notificationItem.classList.remove('unread');
        
        const unreadCount = document.querySelectorAll('.notification-item.unread').length;
        if (unreadCount === 0) {
            document.querySelectorAll('.nav-badge').forEach(badge => {
                badge.classList.add('hidden');
            });
            document.querySelectorAll('.notification-badge').forEach(badge => {
                badge.classList.add('hidden');
            });
        }
        
        showToast('通知已标为已读');
    });
});

// 通知筛选
function filterNotifications(filter) {
    notificationItems.forEach(item => {
        if (filter === 'all') {
            item.style.display = 'flex';
        } else if (filter === 'unread') {
            if (item.classList.contains('unread')) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        } else if (filter === 'lab') {
            const icon = item.querySelector('.notification-icon i');
            if (icon.classList.contains('fa-home') || icon.classList.contains('fa-flask') || 
                icon.classList.contains('fa-users') || icon.classList.contains('fa-exclamation-triangle')) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        } else if (filter === 'course') {
            const icon = item.querySelector('.notification-icon i');
            if (icon.classList.contains('fa-book') || icon.classList.contains('fa-calendar') || 
                icon.classList.contains('fa-trophy')) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        }
    });
}

notificationFilter.addEventListener('change', () => {
    filterNotifications(notificationFilter.value);
});

notificationsFilterPage.addEventListener('change', () => {
    filterNotifications(notificationsFilterPage.value);
});

// 提示消息
function showToast(message, success = true) {
    toastMessage.textContent = message;
    const icon = toast.querySelector('i');
    
    if (success) {}}